<script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch } from 'vue';

import { Pagination, Table } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';

// 引入 columns 数组
import columns from './columns';

// 引入 ListItem 类型
import type { ListItem } from './columns';

import dayjs from 'dayjs';

import { getFinanceOrderList } from '#/api';

const [QueryForm, formApi] = useVbenForm({
  // 默认展开
  collapsed: false,
  // 所有表单项共用，可单独在表单内覆盖
  commonConfig: {
    // 所有表单项
    componentProps: {
      class: 'w-full',
    },
  },
  handleSubmit: onSubmit,
  handleReset: onReset,
  layout: 'horizontal',
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入订单号',
        allowClear: true,
      },
      fieldName: 'orderNo',
      label: '订单号',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入客人姓名',
        allowClear: true,
      },
      fieldName: 'contactName',
      label: '客人姓名',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入客人联系电话',
        allowClear: true,
        type: 'number',
      },
      fieldName: 'contactPhone',
      label: '客人电话',
    },
    {
      component: 'RangePicker',
      fieldName: 'startDatePicker',
      label: '入住时间',
    },
    {
      component: 'RangePicker',
      fieldName: 'endDatePicker',
      label: '离店时间',
    },
  ],
  // 是否可展开
  showCollapseButton: false,
  submitButtonOptions: {
    content: '查询',
  },
  wrapperClass: 'grid-cols-1 md:grid-cols-3',
});

// 分页器
const pagination = ref({
  pageSize: 20,
  pageNo: 1,
});
const total = ref(0);

// 表单数据是否加载中
const loading = ref<boolean>(true);

// 查询表单数据
const formData = ref({});

// 使用导入的 ListItem 类型
const list = ref<ListItem[]>([]);

// 查询接口
const getList = async () => {
  try {
    const { data } = await getFinanceOrderList({
      ...formData.value,
      ...pagination.value,
    });
    list.value = data?.records || [];
    total.value = data?.total || 0;
    const time = setTimeout(() => {
      loading.value = false;
      clearTimeout(time);
    }, 400);
  } catch (error) {
    loading.value = false;
    console.error('获取财务列表失败：', error);
  }
};

// 分页改变事件
const onPageChange = (page: number, pageSize: number) => {
  pagination.value.pageNo = page || 1;
  pagination.value.pageSize = pageSize || 10;
  loading.value = true;
  getList();
};

// 查询事件
function onSubmit(values: Record<string, any>) {
  formData.value = {
    ...values,
    startCheckInDate: values.startDatePicker
      ? dayjs(values.startDatePicker[0]).format('YYYY-MM-DD')
      : '',
    endCheckInDate: values.startDatePicker
      ? dayjs(values.startDatePicker[1]).format('YYYY-MM-DD')
      : '',
    startCheckOutDate: values.endDatePicker
      ? dayjs(values.endDatePicker[0]).format('YYYY-MM-DD')
      : '',
    endCheckOutDate: values.endDatePicker
      ? dayjs(values.endDatePicker[1]).format('YYYY-MM-DD')
      : '',
  };
  pagination.value.pageNo = 1;
  loading.value = true;
  total.value = 0;
  getList();
}

// 重置事件
function onReset() {
  formApi.resetForm();
  pagination.value.pageNo = 1;
  loading.value = true;
  total.value = 0;
  formApi.submitForm();
}

const scrollY = ref<number>(500);
// 定义获取高度的函数
const getScrollY = () => {
  const height = window.innerHeight;
  const main = document.querySelector('#main') as HTMLElement;
  if (height < 500) {
    scrollY.value = 300;
  } else if (main) {
    const top = main.getBoundingClientRect().top;
    scrollY.value = height - top - 160;
  }
};
// 初始化
onMounted(() => {
  getList();
  getScrollY();
  // 监听窗口大小变化
  window.addEventListener('resize', getScrollY);
});
// 组件卸载时移除监听
onUnmounted(() => {
  window.removeEventListener('resize', getScrollY);
});
// 监听 DOM 变化，确保 main 元素加载完成后更新高度
watch(
  () => document.querySelector('#main'),
  (newValue) => {
    if (newValue) {
      getScrollY();
    }
  },
  { immediate: true },
);

// 订单类型
const orderTypeText: { [key: number]: string } = {
  1: '新定',
  2: '修改',
  3: '续住',
  4: '取消',
};
</script>

<template>
  <div class="absolute bottom-0 right-0 h-[100%] w-[100%] overflow-hidden">
    <div class="flex h-[100%] w-[100%] flex-col overflow-auto p-5 pt-4">
      <div class="mb-4 text-xl font-bold">财务明细</div>
      <div class="card-box w-full pr-5 pt-6">
        <QueryForm />
      </div>
      <div id="main" class="card-box relative mt-4 w-full p-4">
        <Table
          :columns="columns"
          :data-source="list"
          :loading="loading"
          :pagination="false"
          :scroll="{ x: 1300, y: scrollY }"
          bordered
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'orderType'">
              <p>{{ orderTypeText[record.orderType] }}</p>
            </template>
          </template>
        </Table>
        <div v-if="total > 0" class="flex justify-end pt-4">
          <Pagination
            v-model:current="pagination.pageNo"
            v-model:page-size="pagination.pageSize"
            :total="total"
            @change="onPageChange"
          />
        </div>
      </div>
    </div>
  </div>
</template>
